package com.example.lenovo.asia5b.my.order.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.example.lenovo.asia5b.home.bean.BdShippingBean;
import com.example.lenovo.asia5b.home.bean.ShippingBean;
import com.example.lenovo.asia5b.my.activity.AddressActivity;
import com.example.lenovo.asia5b.my.activity.SetPayPassword;
import com.example.lenovo.asia5b.my.bean.AddressBean;
import com.example.lenovo.asia5b.my.bean.ShippingPersonBean;
import com.example.lenovo.asia5b.my.myWallet.activity.MyWalletActivity;
import com.example.lenovo.asia5b.my.order.adapter.ConfirmOrderAdapter;
import com.example.lenovo.asia5b.my.order.bean.ConfirmOrderBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;


/**
 * Created by lenovo on 2017/6/28.
 */

public class ConfirmOrderActivity extends BaseActivity implements ICallBack, LoadingDalog.PasswordDialogInterface{

    private LayoutInflater inflater;
    private ListView listView;
    private View header;
    private View botton;
    private ConfirmOrderAdapter adapter;
    private Dialog mDialog,showTipsDialog;
    private String order_id;
    private LoadingDalog loadingDalog;
    private List<ConfirmOrderBean> lists ;
    private TextView txt_number,txt_goods_amount,txt_pay_points,txt_poundage,txt_bdpsf,txt_transport_money,txt_insurance,txt_transport_hint;
    private TextView txt_consignee,txt_mobile,txt_address,txt_tips;
    private Switch sc_insurance,sc_pay_points;
    private Spinner spr_bonus;
    private Spinner spr_shipping,spr_transport;
    //收货地址ID，收货人ID,国际运输ID，本地运输ID
    private String  address_id="",contact_id="",shipping_id="",transport_id="",shipping_type="3492";;
    private List<ShippingBean> listShipping = new ArrayList<ShippingBean>();
    private List<BdShippingBean> listbdShipping = new ArrayList<BdShippingBean>();
    //地址
    private LinearLayout frame_order_address,ll_explain;
    //保险费
    private  float pack_fee_fl;
    //保险费2
    private  float pack_fee_fl_2;
    //积分
    private  int rm_fl = 0;
    //积分2
    private  int rm_fl_2 = 0;
    //总金额
    private  float total;
    //代金券
    private  String bonus_id="";
    //杂费
    private  float incidentals;
    //只调用一次
    private boolean isOne,isTwo,isThree;
    private boolean isMergePayments;
    //区分是普通付款还是特殊付款
    private String is_merge="0",is_specail="0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frame_confirm_order);
        initView();
        bdShippingData();
    }

    private void initView(){
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.public_title_name).text(getResources().getString(R.string.qrdd));
        F.id(R.id.order_payment).clicked(this);
        F.id(public_btn_left).clicked(this);
        inflater = LayoutInflater.from(this);
        listView = this.findViewById(R.id.frame_confirm_order);

        header = (View)inflater.inflate(R.layout.frame_confirm_order_header_2,null);
        botton = (View)inflater.inflate(R.layout.frame_confirm_order_botton,null);

        ll_explain= (LinearLayout) botton.findViewById(R.id.ll_explain);
        ll_explain.setOnClickListener(this);

        txt_number= (TextView)botton.findViewById(R.id.txt_number);
        txt_goods_amount = (TextView)botton.findViewById(R.id.txt_goods_amount);
        txt_pay_points= (TextView)botton.findViewById(R.id.txt_pay_points);
        sc_insurance= (Switch) botton.findViewById(R.id.sc_insurance);
        sc_pay_points= (Switch) botton.findViewById(R.id.sc_pay_points);
        spr_bonus =(Spinner) botton.findViewById(R.id.spr_bonus);
        txt_poundage = (TextView)botton.findViewById(R.id.txt_poundage);
        txt_bdpsf = (TextView)botton.findViewById(R.id.txt_bdpsf);
        txt_insurance = (TextView)botton.findViewById(R.id.txt_insurance);
        txt_transport_money = (TextView)botton.findViewById(R.id.txt_transport_money);
        txt_transport_hint= (TextView)botton.findViewById(R.id.txt_transport_hint);

        txt_consignee = (TextView) header.findViewById(R.id.txt_consignee);
        txt_mobile  = (TextView) header.findViewById(R.id.txt_mobile);
        txt_address = (TextView) header.findViewById(R.id.txt_address);
        spr_shipping = (Spinner) header.findViewById(R.id.spr_shipping);
        spr_transport = (Spinner) header.findViewById(R.id.spr_transport);
        frame_order_address = (LinearLayout)header.findViewById(R.id.frame_order_address);
        frame_order_address.setOnClickListener(this);
//        txt_shipping_name = (TextView)header.findViewById(txt_shipping_name);
//        txt_transport= (TextView)header.findViewById(txt_transport);
//        image_order_arrows = (ImageView) header.findViewById(R.id.image_order_arrows);
//        image_order_arrows.setVisibility(View.INVISIBLE);

        listView.addHeaderView(header);
        listView.addFooterView(botton);

        adapter = new ConfirmOrderAdapter(this);
        listView.setAdapter(adapter);
        Intent intent = getIntent();
        order_id = intent.getStringExtra("order_id");
        if (intent.hasExtra("mergePayments")) {
            isMergePayments = true;
        }
        if (intent.hasExtra("is_specail")){
            is_specail = intent.getStringExtra("is_specail");
        }
        if (intent.hasExtra("is_merge")){
            is_merge = intent.getStringExtra("is_merge");
        }

        sc_insurance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //打钩就添加保险费
                if (sc_insurance.isChecked()) {
                    pack_fee_fl = pack_fee_fl_2;
                } else {
                    pack_fee_fl = 0;
                }
                calculate();
            }
        });
        sc_pay_points.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //打钩就添加积分
                if (sc_pay_points.isChecked()) {
                    rm_fl =  rm_fl_2;
                } else {
                    rm_fl =   0;
                }
                if (rm_fl > 0) {
                    //当用户同时使用积分和代金券时候，要是杂费小余哪一个都不让用户点击
                    if (type_money_int_t>0 &&type_money_int_t > incidentals + pack_fee_fl){
                        pack_fee_fl = 0;
                        sc_pay_points.setChecked(false);
                        U.Toast(ConfirmOrderActivity.this,getResources().getString(R.string.zfyjqbdk));
                        return;
                    }
                }
                calculate();
            }
        });
    }

    private void initDialog(String tips){
        if (showTipsDialog == null){
            showTipsDialog = new Dialog(this);
            showTipsDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            View view = LayoutInflater.from(this).inflate(R.layout.activity_tips_view, null);
            view.setBackgroundColor(Color.parseColor("#00000000"));
            txt_tips = (TextView) view.findViewById(R.id.txt_tips);

            showTipsDialog.setContentView(view);
            showTipsDialog.setCanceledOnTouchOutside(true);
            Window dialogWindow = showTipsDialog.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
//            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//            lp.height = DensityUtil.dip2px(this, 430);
            lp.gravity = Gravity.CENTER;
//            dialogWindow.setBackgroundDrawableResource(R.color.transparent_all);
            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
            p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6
            p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.85
            dialogWindow.setAttributes(lp);
        }
        txt_tips.setText(tips);
        showTipsDialog.show();

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.ll_explain:
                initDialog("Note:\n" +
                        "1. The international shipping fee is calculated as price/0.5kg.\n" +
                        "2. The processing fee is calculated as 2%.\n" +
                        "3. The local delivery fee is calculated as price/1kg.\n" +
                        "4. The Parcel Handling Guarantee is calculated as 3%\n" +
                        " \n" +
                        "Please refer to our “international shipping & local delivery” page for details.\n" +
                        " \n" +
                        "Please take note that purchased goods will only be dispatched in one batch when all the goods arrived at Asia5b China warehouse, unless stated otherwise.\n");
                break;

            case R.id.order_payment:
                if (null == lists){
                    return;
                }
                String ids ="";
                for (int i = 0; i < lists.size(); i++) {
                    ConfirmOrderBean bean  = lists .get(i);
                    if (bean.isSelected) {
                        ids = ids + bean.rec_id + ",";
                    }
                }
                if (TextUtils.isEmpty(ids)){
                    U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.spslbnw0));
                    return;
                }
                if (getUserBean().paypass.equals("0")){
                    U.Toast(ConfirmOrderActivity.this, getString(R.string.none_pay_pwd));
                    intent = new Intent(ConfirmOrderActivity.this, SetPayPassword.class);
                    startActivity(intent);
                    return;
                }
                String mon = F.id(R.id.txt_total).getText().toString();
                if (mon.length() >= 3) {
                    loadingDalog.showPassword(mon.replaceAll("RM ",""));
                }
                break;
            case public_btn_left:
                if (isMergePayments) {
                    intent = new Intent();
                    intent.putExtra("2222", 2222);
                    this.setResult(0, intent);
                }
                finish();
                break;
            case R.id.frame_order_address:
                startActivityForResult(new Intent(ConfirmOrderActivity.this,AddressActivity.class),0);
                break;
            default:
                break;
        }
    }

    @Override
    public void gainPasswor(String strPasswor) {
        dropPayData(strPasswor);
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONObject order = json.getJSONObject("order");
                            JSONArray goods_list = order.getJSONArray("goods_list");
                            lists = Logic.getListToBean(goods_list, new ConfirmOrderBean());
                            adapter.setLists(lists);
                            adapter.notifyDataSetChanged();
                            //本地配送方式
                            String shipping_name = order.getString("shipping_name");
                            String shipping_id = order.getString("shipping_id");

                            for (int q = 0; q< listbdShipping.size();q++){
                                if (shipping_id.equals(listbdShipping.get(q).shipping_id)){
                                    spr_shipping.setSelection(q);
                                    break;
                                }
                            }
//                            txt_shipping_name.setText(shipping_name);
                            //国际配送方式
                            String transport = order.getString("transport");
                            transport_id = order.getString("transport_id");
                            shipping_type = order.getString("type");
//                            txt_transport.setText(transport);
                            //商品总价
                            String goods_amount = order.getString("goods_amount");
                            //商品数量
                            txt_number.setText("" + order.getString("goods_num"));
                            //收货人姓名
                            String consignee = order.getString("consignee");
                            txt_consignee.setText(consignee);
                            //收货人电话
                            String mobile = order.getString("mobile");
                            txt_mobile.setText( mobile);
                            //收货人地址
                            String address = order.getString("address");
                            String province = order.getString("province");
                            String country = order.getString("country");
                            txt_address.setText(address+province+country);

                            JSONObject user = json.getJSONObject("user");
                            JSONArray bonus = user.getJSONArray("bonus");
                            //代金券列表
                            List<Map<String,String>> bonusLists = new ArrayList<Map<String,String>>();
                            Map<String,String> map1 = new HashMap<String,String>();
                            map1.put("bonus_id","0");
                            map1.put("type_money",getString(R.string.qxz));
                            bonusLists.add(map1);
                            for (int i = 0; i  < bonus.length(); i++) {
                                Map<String,String> map = new HashMap<String,String>();
                                map.put("bonus_id",bonus.getJSONObject(i).getString("bonus_id"));
                                map.put("type_money",bonus.getJSONObject(i).getString("type_money"));
                                bonusLists.add(map);
                            }
                            showBonusData(bonusLists);
                            //用户积分
                            String pay_points = user.getString("pay_points");
                            int pay_points_int = Integer.parseInt(pay_points);
                            //少于100积分不给选
                            if (pay_points_int < 100) {
                                //想办法不让g给选成功
                                sc_pay_points.setVisibility(View.GONE);
                                txt_pay_points.setText(getResources().getString(R.string.myksyjf));
                            } else {
                                //小于1000积分
                                if (pay_points_int < 1000) {
                                    //将积分化为整数
                                    pay_points_int = pay_points_int/100*100;
                                    //积分变成马币
                                    rm_fl = pay_points_int / 100;
                                    txt_pay_points.setText(getResources().getString(R.string.nyzdksy)+pay_points_int+
                                            getResources().getString(R.string.integral)+","+getResources().getString(R.string.kdk)+rm_fl+"RM");
                                } else {
                                    rm_fl = 10;
                                    txt_pay_points.setText(getResources().getString(R.string.nyzd1000)+rm_fl+"RM");
                                }
                            }

                            //保险费
                            String pack_fee = order.getString("pack_fee");
                            //先默认为 保险费为这个
                            pack_fee_fl = Float.parseFloat(pack_fee);

                            //本地派送费
                            String pay_fee = order.getString("pay_fee");
                            txt_bdpsf.setText("RM "+pay_fee);
                            //手续费
                            String tax = order.getString("tax");
                            txt_poundage.setText("RM "+tax);

                            //国际运输费
                            String insure_fee_str = order.getString("insure_fee");
                            txt_transport_money.setText("RM "+insure_fee_str);
                            //杂费=本地派送费+手续费+国际运输费+保险费
                            incidentals = Float.parseFloat(pay_fee) + Float.parseFloat(tax) + Float.parseFloat(insure_fee_str);


                            float fee = 0;
                            //中国运输费
                            String shipping_fee_str = order.getString("shipping_fee");
                            txt_goods_amount.setText("RM " + getScale(Float.parseFloat(shipping_fee_str)+Float.parseFloat(goods_amount)));
                            //商品费用+国际运输费+中国运输费
                            fee =  Float.parseFloat(goods_amount)+  Float.parseFloat(insure_fee_str)+ Float.parseFloat(shipping_fee_str);
                            //保险费为0，就默认显示保险费，否则开始计算
                            boolean isPackFee = false;
                            if (pack_fee_fl!=0) {
                                isPackFee = true;
                            } else {
                                //计算保险费
                                //保险费率
                                String premium = json.getString("premium");
                                float premium_fl = Float.parseFloat(premium);
                                //乘以保险费率 等于保险费
                                pack_fee_fl  = fee* premium_fl;
                                //打钩就增加保险费
//                            if (sc_insurance.isChecked()) {
//                                total =  total+ pack_fee_fl;
//                                incidentals = incidentals + pack_fee_fl;
//                            }
                            }
                            //商品费用+国际运输费+中国运输费+本地派送费+手续费=总钱
                            total =  fee+Float.parseFloat(pay_fee)+Float.parseFloat(tax);
                            //重量
                            txt_transport_hint.setText("("+getResources().getString(R.string.sjzl)+"="+order.getString("order_weight")+"KG;"+
                                    getResources().getString(R.string.jfzl)+"="+order.getString("fee_weight")+"KG)");
                            pack_fee_fl_2 = pack_fee_fl;
                            pack_fee_fl = 0;
                            rm_fl_2 = rm_fl;
                            rm_fl = 0;
                            //最终合计
                            F.id(R.id.txt_total).text("RM " +getScale(total));
                            if (isPackFee) {
                                sc_insurance.setChecked(true);
                            }
                        }else if (state == 1) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                shippingData();
                loadingDalog.dismiss();
                isTwo = true;
            }  if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        loadingDalog.clearPassword();
                        if (state == 0) {
                            U.Toast(ConfirmOrderActivity.this,getString(R.string.cg));
//                            colseActivity("com.example.lenovo.asia5b.my.order.activity.MergePaymentsActivity");
                            Intent intent = new Intent();
                            intent.putExtra("confirm",2222);
                            ConfirmOrderActivity.this.setResult(0, intent);
                            finish();
                        }
                        else if (state == 1) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.mysj));
                        } else if (state == 4) {
                            U.Toast(ConfirmOrderActivity.this,getString(R.string.mnmdjf));
                        } else if (state == 5) {
                            U.Toast(ConfirmOrderActivity.this, getString(R.string.mmcw));
                        } else if (state == 6) {
                            U.Toast(ConfirmOrderActivity.this,getString(R.string.yebz));
                            Intent intent = new Intent(ConfirmOrderActivity.this, MyWalletActivity.class);
                            loadingDalog.dismiss();
                            loadingDalog.passwordDialog = null;
                            startActivity(intent);
                        }else if (state == 10) {
                            U.Toast(ConfirmOrderActivity.this, getString(R.string.none_pay_pwd));
                            Intent intent = new Intent(ConfirmOrderActivity.this, SetPayPassword.class);
                            startActivity(intent);
                            loadingDalog.dismiss();
                            loadingDalog.passwordDialog = null;
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 2 || action == 5) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        loadingDalog.clearPassword();
                        if (state == 0) {
                            JSONObject order = json.getJSONObject("fee");
                            //保险费
                            String pack_fee = order.getString("pack_fee");
                            //先默认为 保险费为这个
                            pack_fee_fl = Float.parseFloat(pack_fee);

                            //商品数量
                            txt_number.setText("" + order.getString("goods_num"));

                            //本地派送费
                            String pay_fee = order.getString("pay_fee");
                            txt_bdpsf.setText("RM "+pay_fee);
                            //手续费
                            String tax = order.getString("tax");
                            txt_poundage.setText("RM "+tax);
                            //国际运输费
                            String insure_fee_str = order.getString("insure_fee");
                            txt_transport_money.setText("RM "+insure_fee_str);
                            //杂费=本地派送费+手续费+国际运输费+保险费
                            incidentals = Float.parseFloat(pay_fee) + Float.parseFloat(tax) + Float.parseFloat(insure_fee_str);
                            float fee = 0;
                            //中国运输费
                            String shipping_fee_str = order.getString("shipping_fee");
                            //商品总价
                            String goods_amount = order.getString("goods_amount");
                            txt_goods_amount.setText("RM " + getScale(Float.parseFloat(shipping_fee_str)+Float.parseFloat(goods_amount)));
                            //商品费用+国际运输费+中国运输费
                            fee =  Float.parseFloat(goods_amount)+  Float.parseFloat(insure_fee_str)+ Float.parseFloat(shipping_fee_str);
                            //保险费为0，就默认显示保险费，否则开始计算
                            if (pack_fee_fl!=0) {
                            } else {
                                //计算保险费
                                //保险费率
                                String premium = order.getString("premium");
                                float premium_fl = Float.parseFloat(premium);
                                //乘以保险费率 等于保险费
                                pack_fee_fl  = fee* premium_fl;
                            }
                            //商品费用+国际运输费+中国运输费+本地派送费+手续费=总钱
                            total =  fee+Float.parseFloat(pay_fee)+Float.parseFloat(tax);
                            //重量
                            txt_transport_hint.setText("("+getResources().getString(R.string.sjzl)+"="+order.getString("order_weight")+"KG;"+
                                    getResources().getString(R.string.jfzl)+"="+order.getString("fee_weight")+"KG)");
                            pack_fee_fl_2 = pack_fee_fl;
                            pack_fee_fl_2 = pack_fee_fl;
                            pack_fee_fl = 0;
                            //最终合计
                            F.id(R.id.txt_total).text("RM " +getScale(total));
                            if (action == 5) {
                                for (int i = 0;i < adapter.getCount();i++){
                                    adapter.getLists().get(i).isSelected = true;
                                }
                                adapter.notifyDataSetChanged();
                                sc_insurance.setVisibility(View.VISIBLE);
                                sc_pay_points.setVisibility(View.VISIBLE);
                                spr_bonus.setVisibility(View.VISIBLE);
                                sc_insurance.setChecked(false);
                                sc_pay_points.setChecked(false);
                                spr_bonus.setSelection(0);
                            }
                        }
                        else if (state == 1) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            else if (action == 3) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bd_shipping = json.getJSONArray("shipping");
                             listbdShipping = Logic.getListToBean(bd_shipping, new BdShippingBean());
                            showBdShippingData();
                        } else if (state == 1) {
                            U.Toast( ConfirmOrderActivity.this, getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
                MyPointsData();
            }
            else if (action == 4) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject shipping = json.getJSONObject("feight");
                            JSONArray shippingList = shipping.getJSONArray(shipping_type);
                            listShipping = Logic.getListToBean(shippingList, new ShippingBean());
                            showBdBdShippingData();
                        } else if (state == 1) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.qmsb)
                            );
                        } else if (state == 2) {
                            U.Toast(ConfirmOrderActivity.this, getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
            }

        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 我的订单接口
     */
    public void MyPointsData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.PAY_ORDER;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"order_id"+order_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",""+order_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            parmaMap.put("is_merge",is_merge);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }
    }

    /**
     * 确认付款接口
     */
    public void dropPayData(String paypass) {
        loadingDalog.dismiss();
        loadingDalog.show();
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.DROP_PAY;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            //包裹ID集
            String ids = "";
            //积分
            int jifen = 0 ;
            //当杂费小余积分费用时，扣除相应的积分
            if (incidentals2 < rm_fl) {
                jifen = (int)incidentals2;
                //要是杂费有小数点就加1
                if (incidentals2%1!=0) {
                    jifen = jifen +1;
                }
                jifen = jifen*100;
            } else {
                jifen = rm_fl*100 ;
            }
            //代金券ID
            String bonus = bonus_id;
            for (int i = 0; i < lists.size(); i++) {
                ConfirmOrderBean bean  = lists .get(i);
                if (bean.isSelected) {
                    //不包含
                    if (ids.indexOf(bean.rec_id)== -1) {
                        ids = ids + bean.rec_id + ",";
                    }
                }
            }
            ids = ids.substring(0,ids.length()-1);
            // 确认是否买保险费，0：未买，1：买了
            String insurance = "0";
            if ( sc_insurance.isChecked()) {
                insurance = "1";
            }
            String[] sort = {"user_id"+user_id,"order_id"+order_id,"ids"+ids,"insurance"+insurance,"jifen"+jifen,"bonus"+bonus,"paypass"+paypass,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",""+order_id);
            parmaMap.put("ids",""+ids);
            parmaMap.put("insurance",""+insurance);
            parmaMap.put("jifen",""+jifen);
            parmaMap.put("bonus",""+bonus);
            parmaMap.put("paypass",""+paypass);
            parmaMap.put("time",time);

            parmaMap.put("address_id",address_id);
            parmaMap.put("contact_id",contact_id);
            parmaMap.put("shipping_id",shipping_id);
            parmaMap.put("transport",transport_id);

            parmaMap.put("sign",md5_32);
            parmaMap.put("pay_equipment","Android");
            parmaMap.put("is_merge",is_merge);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            if (null != mDialog) {
                if (mDialog.isShowing()) {
                    mDialog.dismiss();
                    loadingDalog.dismiss();
                } else {
                    if (isMergePayments) {
                        Intent intent = new Intent();
                        intent.putExtra("2222",2222);
                        this.setResult(0, intent);
                    }
                    finish();
                }
            }else {
                if (isMergePayments) {
                    Intent intent = new Intent();
                    intent.putExtra("2222",2222);
                    this.setResult(0, intent);
                }
                finish();
            }

        }

        return false;

    }

    public String getScale(float total) {

        if(total != 0.00){
            if (total < 1){
                BigDecimal bg = new BigDecimal(total);
                return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"";
            }else {
                java.text.DecimalFormat df = new java.text.DecimalFormat("########.00");
                return df.format(total);
            }
        }else{
            return "0.00";
        }
    }
    int type_money_int_t = 0;
    //代金券选择器
    public void showBonusData(final List<Map<String,String>> bonusLists) {
        List<String > listNameOnes=new ArrayList<String>();
        for (int i = 0; i <bonusLists.size(); i++) {
            Map<String,String> bean = bonusLists.get(i);
            String cityname = bean.get("type_money");
            listNameOnes.add(cityname);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ConfirmOrderActivity.this,
                R.layout.simple_list_item,
                listNameOnes);
        spr_bonus.setAdapter(adapter1);
        spr_bonus.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                bonus_id = bonusLists.get(arg2).get("bonus_id");
                String type_money  = bonusLists.get(arg2).get("type_money");
                int type_money_int = 0;
                if (!type_money.equals(getString(R.string.qxz))) {
                    type_money_int = (int)(Float.parseFloat(type_money));
                }
                type_money_int_t = type_money_int;
                //只调用一次
                if (isOne) {
                    if (type_money_int_t>0) {
                        //当用户同时使用积分和代金券时候，要是杂费小余哪一个都不让用户点击
                        if (rm_fl > 0 && rm_fl > incidentals + pack_fee_fl) {
                            if (type_money_int_t > 0) {
                                //以防万一，将值都设为0
                                bonus_id = "0";
                                type_money_int_t = 0;
                                U.Toast(ConfirmOrderActivity.this,getResources().getString(R.string.zfyjqbdk));
                                spr_bonus.setSelection(0);
                                return;
                            }
                        }
                    }
                    calculate();
                } else {
                    isOne = true;
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

    }
    float incidentals2;
    /**
     * 计算
     */
    public void calculate() {
        //总价
        float tt = total  -incidentals ;
        //杂费
        incidentals2 = incidentals + pack_fee_fl;
        //其他费
        float ll = 0;
        //代金券加积分，简称为X
          int  jf_djj = rm_fl +type_money_int_t;
        //假如X大于杂费就减去杂费，反之减去X
        if (jf_djj > incidentals2) {
            ll = 0;
        } else {
            ll = incidentals2 - jf_djj;
        }

        tt = tt +ll ;
        if (sc_insurance.getVisibility() == View.VISIBLE) {
            if (pack_fee_fl >0) {
                txt_insurance.setText("RM" + getScale(pack_fee_fl));
            }else {
                txt_insurance.setText("");
            }
        }
        F.id(R.id.txt_total).text("RM " +getScale(tt));

    }
    //====================================================计算分割线================================================================================
    //当用户对单个Item作出各种操作时，都需要调用这个方法进行刷新
    public void settlementSum() {
        float totalPrice = 0;
        String ids ="";
        for (int i= 0;  i < adapter.getLists().size();i++) {
            ConfirmOrderBean bean = adapter.getLists().get(i);
            if (!bean.isSelected) {
                float price = Float.parseFloat(bean.goods_price);
                int num = Integer.parseInt(bean.goods_number);
                totalPrice = totalPrice + price* num;
            } else {
                ids = ids + bean.rec_id + ",";
            }
        }
        if (TextUtils.isEmpty(ids)) {
            F.id(R.id.txt_total).text("RM " +"0.0");
            txt_goods_amount.setText("RM " + "0.0");
            txt_bdpsf.setText("RM "+"0.0");
            txt_poundage.setText("RM "+"0.0");
            txt_transport_money.setText("RM "+"0.0");
            txt_number.setText("0 ");
            if (sc_insurance.getVisibility() == View.VISIBLE) {
                txt_insurance.setText("");
            }
            //重量
            txt_transport_hint.setText("("+getResources().getString(R.string.sjzl)+"="+"0"+"KG;"+
                    getResources().getString(R.string.jfzl)+"="+"0"+"KG)");
            pack_fee_fl_2 = pack_fee_fl;
            total = 0;
            sc_insurance.setVisibility(View.INVISIBLE);
            sc_pay_points.setVisibility(View.INVISIBLE);
            spr_bonus.setVisibility(View.INVISIBLE);
        } else {
            if (sc_insurance.getVisibility() == View.VISIBLE) {
//                txt_insurance.setText("RM " + "0.0");
                txt_insurance.setText("");
            }
            sc_insurance.setVisibility(View.VISIBLE);
            sc_pay_points.setVisibility(View.VISIBLE);
            spr_bonus.setVisibility(View.VISIBLE);
            sc_insurance.setChecked(false);
            sc_pay_points.setChecked(false);
            spr_bonus.setSelection(0);
            rm_fl  = 0;
            ids = ids.substring(0,ids.length()-1);
            jiSuan(ids);
        }
    }

    public void jiSuan(String ids) {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.JS_FEE;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"order_id"+order_id,"rec_ids"+ids,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",""+order_id);
            parmaMap.put("rec_ids",""+ids);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            parmaMap.put("is_merge",is_merge);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        }catch (Exception e) {

        }
    }

    //本地派送选择器
    public void showBdShippingData() {
        List<String > listNameOnes=new ArrayList<String>();
        for (int i = 0; i <listbdShipping.size(); i++) {
            BdShippingBean bean = listbdShipping.get(i);
            String cityname = bean.shipping_name;
            listNameOnes.add(cityname);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ConfirmOrderActivity.this,
                R.layout.simple_list_item,
                listNameOnes);
        spr_shipping.setAdapter(adapter1);
        spr_shipping.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (isTwo) {
                    shipping_id = listbdShipping.get(arg2).shipping_id;
                    reselection();
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

    }

    //国际派送选择器
    public void showBdBdShippingData() {
        List<String > listNameOnes=new ArrayList<String>();
        for (int i = 0; i <listShipping.size(); i++) {
            ShippingBean bean = listShipping.get(i);
            String cityname = bean.transport;
            listNameOnes.add(cityname);
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(ConfirmOrderActivity.this,
                R.layout.simple_list_item,
                listNameOnes);
        spr_transport.setAdapter(adapter1);
        spr_transport.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (isTwo) {
                    if (isThree) {
                        transport_id = listShipping.get(arg2).transport_id;
                        reselection();
                    } else {
                        isThree = true;
                    }
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

        for (int i = 0; i <listShipping.size(); i++) {
            if (transport_id.equals(listShipping.get(i).transport_id)){
                if (i == 0) {
                    isThree = true;
                }
                spr_transport.setSelection(i);
                break;
            }
        }
    }

    /**
     * 本地运输方式
     */
    public void bdShippingData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.BD_SHIPPING;
        JsonTools.getJsonAll(this, url, parmaMap, 3);
    }

    /**
     * 国际运输方式
     */
    public void shippingData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.SHIPPING;
        parmaMap.put("type",is_specail);
        JsonTools.getJsonAll(this, url, parmaMap, 4);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(resultCode){
            case 0:
                if (null !=data) {
                    if (data.hasExtra("AddressBean")) {
                        //当点击地址Item回来的时候
                        AddressBean bean = (AddressBean)data.getSerializableExtra("AddressBean");
                        txt_address.setText(bean.address+bean.province+bean.country_2);
                        address_id = bean.address_id;
                        shipping_type = bean.type;
                        reselection();
                        shippingData();
                    } else if (data.hasExtra("ShippingPersonBean")) {
                        //当点击地址Item回来的时候
                        ShippingPersonBean bean = (ShippingPersonBean)data.getSerializableExtra("ShippingPersonBean");
                        txt_consignee.setText(bean.consignee);
                        txt_mobile.setText(bean.mobile);
                        contact_id = bean.contact_id;
                        reselection();
                    }
                }
                break;
        }
    }


    public void reselection() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.RESELECTION;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"order_id"+order_id,"address_id"+address_id,"contact_id"+contact_id,
                    "shipping_id"+shipping_id,"transport"+transport_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",order_id);
            parmaMap.put("address_id",address_id);
            parmaMap.put("contact_id",contact_id);
            parmaMap.put("shipping_id",shipping_id);
            parmaMap.put("transport",transport_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            parmaMap.put("is_merge",is_merge);
            JsonTools.getJsonAll(this, url, parmaMap, 5);
        }catch (Exception e) {

        }
    }

}
